import os
import datetime

import requests
from data_file_analysis.yaml_analysis import YamlAnalysis as ya
from logs.logger import Logger


class Base():

    def __init__(self, url):
        cur_path = os.path.abspath(os.path.dirname(__file__))  # 获取当前文件目录
        root_path = os.path.dirname(cur_path)
        time_now = datetime.datetime.now()
        time_now1 = f'{str(time_now.year)}_{str(time_now.month)}_{str(time_now.day)}_{str(time_now.hour)}_{str(time_now.minute)}'
        self.log = Logger(f'{root_path}/logs/info/{time_now1}_info.log', level='info')
        self._url = url

    def http_request(self, file_path, api_action, header=None, params=None):
        self.log.logger.info(f'{api_action}:')
        api_info = ya.return_yaml_data(file_path, api_action)

        # 日志打印
        self.log.logger.info(f'method:{api_info["method"]}, url:{api_info["url"]}')
        self.log.logger.info(f"params:{params}")

        url = self._url + api_info['url']
        method = api_info['method']

        if method in ["get", "GET", "Get"]:
            self.get_request(url, header)

        elif method in ["post", "POST", "Post"]:
            self.post_request(url, header, params)

        else:
            raise Exception(f'method:{method} is wrong!')

        self.log.logger.info(self.re.json())
        return self.re.json()

    # get请求
    def get_request(self, url, header=None):
        self.re = requests.get(url, headers=header)

    # post请求
    def post_request(self, url, header=None, data=None):
        self.re = requests.post(url, headers=header, json=data)
